<!--
 * @Descripttion: 本地供应商商品管理
 * @version:
 * @Author: 赵致喜
 * @Date: 2020-10-12 11:23:14
 * @LastEditors: 穆宏宇
 * @LastEditTime: 2020-11-25 16:28:32
-->
<template>
  <div>
    <div class="control-box">
      <!-- control 操作区 START -->
      <e-control :search-form-options="formOptions"
                 :search-label-width="searchLabelWidth"
                 :btns="btns"
                 @on-search="searchControlHandle"
                 @on-refresh="refreshControlHandle"
                 @change-height="changeControlHeight"
                 @on-approved="approved"
                 @on-back="back"
                 @on-set="set"
                 @on-cancel="cancel"
				 @upAll="doIt(1)"
				 @downAll="doIt(2)"
                 v-on="$listeners"></e-control>
      <!-- control 操作区 END -->
    </div>
    <div class="table-box">
      <!-- table 数据表格 START -->
      <e-table :data="tableData"
               :columns="columns"
               stripe
               border
               :maxHeight="tableMaxHeight"
               style="width: 100%"
               :tableBtnType="0"
               @selection-change="changeTableSelectData"
               :current="pageData.pageNum"
               :total="pageData.total"
               @page-size-change="changePageSize"
               @page-current-change="changePageCurrent">
        <template slot-scope="{scope}"
                  slot="operation">
<!--          <el-button v-if="tableBtnType === 1 || tableBtnType === 2"-->
<!--                     @click="updateTableHandle(scope.row)"-->
<!--                     type="warning"-->
<!--                     size="mini"-->
<!--                     plain>编辑</el-button>-->
<!--          <el-button v-if="tableBtnType === 1 || tableBtnType === 3"-->
<!--                     @click="deleteTableHandle(scope.row)"-->
<!--                     type="danger"-->
<!--                     size="mini"-->
<!--                     plain>删除</el-button>-->
          <template v-if="operationBtn">
            <el-button v-for="(item, index) in operationBtn"
                       :key="index"
                       :icon="item.icon ? `el-icon-${item.icon}` : ''"
                       v-bind="item.props"
                       size="mini"
                       @click="openDialog(scope.row)">{{item.title}}</el-button>
          </template>
        </template>
        <template slot-scope="{scope}"
                  slot="goodsState">
          {{goodsStateMap[scope.row.goodsState]}}
        </template>
        <template slot-scope="{scope}"
                  slot="isAid">
          {{getAid(scope.row.isAid)}}
        </template>

      </e-table>
      <!-- table 数据表格 END -->
    </div>
    <!-- editDialog 编辑弹窗 START -->

    <el-dialog title="商品详情" :visible.sync="dialogVisible" width="70%" >
      <el-button v-if="dataDetail.goodsState&&dataDetail.goodsState=='COMMIT'" type="success" @click="passGood()">审核通过</el-button>
      <el-button v-if="dataDetail.goodsState&&dataDetail.goodsState=='COMMIT'" type="warning" @click="backGood()">退回修改</el-button>
      <el-button v-if="dataDetail.goodsState&&dataDetail.goodsState=='PASS'" type="danger" @click="upDownGood('DOWN')">商品下架</el-button>
      <el-button v-if="dataDetail.goodsState&&dataDetail.goodsState=='DOWN'" type="success" @click="upDownGood('PASS')">商品上架</el-button>
      <el-form :model="dataDetail" label-width="140px" class="dialog-form">
        <el-row :gutter="20" style="width:95%">
          <el-col :span="12">
            <el-form-item label="规格型号:">{{dataDetail.typeNo}}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="品牌名称:">{{dataDetail.brandName}}</el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20" style="width:95%">
          <el-col :span="12">
            <el-form-item label="商品名称:">{{dataDetail.goodsName}}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="sku:">{{dataDetail.sku}}</el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20" style="width:95%">
          <el-col :span="12">
            <el-form-item label="生产地:">{{dataDetail.goodsArea}}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="进口标识:">{{dataDetail.isImport}}</el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20" style="width:95%">
          <el-col :span="12">
            <el-form-item label="计量单位:">{{dataDetail.saleUnit}}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="含税价格:">{{dataDetail.agreementPrice}}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="未税价格:">{{dataDetail.initExcludeTaxPrice}}</el-form-item>
          </el-col>
		  <el-col :span="12">
		    <el-form-item label="税率:">{{dataDetail.taxRate}}%</el-form-item>
		  </el-col>
        </el-row>
        <el-row :gutter="20" style="width:95%">
          <el-col :span="12">
            <el-form-item label="商品重量:">{{dataDetail.goodsWeight}}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="开始生产日期:">{{dataDetail.produceDate}}</el-form-item>
          </el-col>
        </el-row>
        <el-row  style="width:95%">
          <el-col :span="24">
            <el-form-item label="包装方式:">{{dataDetail.packing}}</el-form-item>
            <el-form-item label="主要图片:">
              <el-image style="width: 150px; height: 150px;" :src="goodsUrl(dataDetail)" fit="fill"></el-image>
            </el-form-item>
            <el-form-item label="一般图片:">  <!-- TODO -->
              <el-image v-for="(goodsImage, index) in dataDetail.goodsImageList" :key="index" style="width: 150px; height: 150px; margin: 0 10px 10px 10px;" :src="`/${goodsImage}`" fit="fill"></el-image>
            </el-form-item>
            <el-form-item label="主属性:">
              <p v-for="(goodsProperty, index) in dataDetail.goodsPropertyList" :key="index">
                {{goodsProperty.key}}：{{goodsProperty.value}}
              </p>
            </el-form-item>
            <el-form-item label="简单配置:">{{dataDetail.goodsParam}}</el-form-item>
            <el-form-item label="商品介绍:">
              <div style="max-width:100%" v-html="dataDetail.goodsIntroduce"></div>
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>
    </el-dialog>

    <!-- editDialog 编辑弹窗 END -->
  </div>
</template>

<script>
import eControl from '@/components/e-control'
import { getListForManage, setGoodsState, setIsAid, getLocalGoodItemDetail,systemHis } from '@/api/admin.api'
import { formOptions, btns } from './control'
import columns from './columns'
import config from '@/config'
import { quillEditor } from 'vue-quill-editor'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
export default {
  name: 'local-supplier-commodity-management',
  components: {
    eControl,
    quillEditor
  },
  props: {
  },
  data () {
    return {
      tableBtnType:"",

      goodsStateMap:{
        COMMIT:"新提交",
        PASS:"审核通过",
        RETURN:"退回修改",
        DOWN:"商品下架"
      },

      // 表格表头
      columns,
      // 表单配置项
      formOptions,
      searchLabelWidth: '100px',
      // 按钮组
      btns,

      // 查询表单
      searchFormData: {},
      // 控制区高度
      controlHeight: 0,
      // 表格数据
      tableData: [],
      // 分页数据
      pageData: {
        // 当前分页
        pageNum: 1,
        // 分页条数
        pageSize: 10,
        // 数据总数
        total: 0
      },
      // 表格选中数据
      tableSelectData: [],

      dialogVisible:false,
      dataId: '',
      dataDetail:{},
      DNS:{}
    }
  },
  watch: {},
  computed: {
    // 商品图片地址
    goodsUrl () {
      return function (item) {
        const host = window.location.host
        const {DNS} = this
        let flag = false
        // 遍历外网地址
        for (let i = 0, max = DNS.outernet.length; i <max; i++) {
          const item = DNS.outernet[i]
          if (item === host) {
            flag = true
            break
          }
        }
        // 外网地址
        if (flag) {
          return `/${item.goodsImagePath}`
        }
        // 内外地址
        else {
          return `/${item.goodsImagePathIntranet}`
        }
      }
    },
    // 组合查询条件和分页
    searchData () {
      const { pageNum, pageSize } = this.pageData
      return { ...this.searchFormData, size: pageSize, current: pageNum }
      // return Object.assign(this.searchFormData,{size: pageSize},{current:pageNum})
    },
    // 表单实例
    dialogForm () {
      return this.$refs.dialogForm
    },
    //表格最大高度
    tableMaxHeight () {
      return window.innerHeight - this.controlHeight - 160
    },
    // 编辑框标题
    editDialogTitle () {
      return this.editDialogType === 0 ? '新增' : '编辑'
    },
    // 操作列自定义按钮
    operationBtn () {
      let btns
      this.columns.map(item => {
        if (item.slotName === 'operation') {
          btns = item.btns || []
        }
      })
      return btns
    }
  },
  methods: {
  doIt(t){
	  if(!this.tableSelectData || this.tableSelectData.length==0){
	    this.$message({
	        message: '请选择待操作的数据',
	        type: 'warning'
	      })
	    return;
	  }
	  let ids = [];
	  var arr = [];
	  for(let data of this.tableSelectData){
	    ids.push(data.id);
		arr.push(data)
	  }
	  var str = '';
	  if(t == 1){
		  str = 'PASS'
	  }else{
		  str = 'DOWN'
	  }
	  setGoodsState(str,ids).then(res => {
	    this.$message({
	        message: '操作成功',
	        type: 'success'
	      })
	    this.getTableData();
		for (var i = 0; i < arr.length; i++) {
			this.dataDetail = arr[i];
			this.changeHistory();
		}
	  })
  },

    getAid(isAid){
      if(isAid == null || isAid==undefined) return '';
      if(isAid) return '是';
      return '否';
    },

    // 初始化表格数据请求
    init () {
      this.getTableData()
    },
    /**
     * @functionName searchControlHandle
     * @param {Object} data 查询参数
     * @description 查询
     * @author 张航
     * @date 2020-09-08 15:01:26
     * @version V1.0.0
     */
    searchControlHandle (data) {
      this.searchFormData = data
      this.refreshPageCurrent()
    },
    /**
     * @functionName refreshControlHandle
     * @param {Object} data 重置后的数据
     * @description 重置查询条件
     * @author 张航
     * @date 2020-09-08 17:01:51
     * @version V1.0.0
     */
    refreshControlHandle (data) {
      this.searchFormData = data
    },
    /**
     * @functionName changeControlHeight
     * @param {String} height 控制区占用高度
     * @description 控制区高度变化
     * @author 张航
     * @date 2020-09-16 16:17:07
     * @version V1.0.0
     */
    changeControlHeight (height) {
      this.controlHeight = height
    },

    /**
     * @functionName changeTableSelectData
     * @param {Array} rows 选中数据
     * @description 表格选中数据改变
     * @author 张航
     * @date 2020-09-08 17:52:12
     * @version V1.0.0
     */
    changeTableSelectData (rows) {
      this.tableSelectData = rows
    },
    /**
     * @functionName checkTableSelectData
     * @return {Number} 返回结果
     * @description 方法描述
     * @author 张航
     * @date 2020-09-10 09:58:59
     * @version V1.0.0
     */
    checkTableSelectData () {
      if (this.tableSelectData.length === 0) {
        this.$alert('至少选择一条数据！', '提示', {
          confirmButtonText: '确定'
        })
      }
      return this.tableSelectData.length
    },
    /**
     * @functionName changePageSize
     * @param {Number} size 分页条数
     * @description 修改分页条数
     * @author 张航
     * @date 2020-09-08 17:57:06
     * @version V1.0.0
     */
    changePageSize (size) {
      this.pageData.pageSize = size
      this.getTableData()
    },
    /**
     * @functionName changePageCurrent
     * @param {Number} current 当前分页
     * @description 修改当前分页
     * @author 张航
     * @date 2020-09-08 18:02:03
     * @version V1.0.0
     */
    changePageCurrent (current) {
      this.pageData.pageNum = current
      this.getTableData()
    },
    /**
     * @functionName refreshPageCurrent
     * @description 重置当前分页
     * @author 张航
     * @date 2020-09-22 10:45:57
     * @version V1.0.0
     */
    refreshPageCurrent () {
      this.pageData.pageNum = 1
      this.getTableData()
    },
    /**
     * @functionName getTableData
     * @description 获取表格数据
     * @author 张航
     * @date 2020-09-08 17:59:45
     * @version V1.0.0
     */
    getTableData () {

      let tmpParam = { ...this.searchFormData, size: this.pageData.pageSize, current: this.pageData.pageNum, goodsSource:"LOCAL_SUPPLIER" }
      if(this.searchFormData.category && this.searchFormData.category.length>0){
        if(this.searchFormData.category[0]){
          tmpParam.primaryCategory = this.searchFormData.category[0];
        }
        if(this.searchFormData.category[1]){
          tmpParam.secondaryCategory = this.searchFormData.category[1];
        }
        if(this.searchFormData.category[2]){
          tmpParam.tertiaryCategory = this.searchFormData.category[2];
        }
      }
      tmpParam.category=null;

      getListForManage(tmpParam).then(res => {
        this.tableData = res.content
        this.pageData.total = res.totalElements
      })
    },
    /**
     * @functionName updateTableHandle
     * @param {Object} row 当前行数据
     * @description 表格编辑按钮
     * @author 张航
     * @date 2020-09-14 16:43:26
     * @version V1.0.0
     */
    updateTableHandle (row) {
      console.log(row)
      this.dialogFormCurrent = { ...row }
      this.openDialog(1)
    },
    /**
     * @functionName deleteTableHandle
     * @param {Object} row 当前行数据
     * @description 表格删除按钮
     * @author 张航
     * @date 2020-09-14 17:17:06
     * @version V1.0.0
     */
    deleteTableHandle (row) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const { id } = row
        const { delete: { url, type = 'GET' } } = this.interFace
        this.interFaceEvent(url, id, type).then(res => {

          // TODO 根据接口调整处理逻辑
          // console.log(res)
          this.$message({
            message: '删除成功',
            type: 'success'
          })
          this.refreshPageCurrent()
        })
      })

    },

    /**
     * @functionName forwardEvent
     * @param {String} name 事件名称
     * @param {*} data 数据
     * @description 转发自定义事件
     * @author 张航
     * @date 2020-09-08 14:51:05
     * @version V1.0.0
     */
    forwardEvent (name, data) {
      this.$emit(name, data)
    },
    /**
     * @functionName interFaceEvent
     * @param {String|} url 请求地址
     * @param {Object} data 请求参数
     * @param {String} type 请求类型，默认为GET
     * @return {Promise} 返回结果
     * @description 接口访问
     * @author 张航
     * @date 2020-09-14 16:14:51
     * @version V1.0.0
     */
    interFaceEvent (url, data, type = 'GET') {
      // let _url = url
      const _type = type.toLowerCase()
      // if (_type === 'get') {
      //   _url = _url + this.$tools.urlParam(data)
      // }
      return this.$api[_type](url, data)
    },

    approved(){
      if(!this.tableSelectData || this.tableSelectData.length==0){
        this.$message({
            message: '请选择待操作的数据',
            type: 'warning'
          })
        return;
      }
      let ids = [];
      for(let data of this.tableSelectData){
        if(!data.goodsState || data.goodsState!='COMMIT'){
          this.$message({
            message: '待操作的商品中，其的状态只可是【新提交】',
            type: 'warning'
          })
          return;
        }
        ids.push(data.id);
      }
      setGoodsState("PASS",ids).then(res => {
        this.$message({
            message: '操作成功',
            type: 'success'
          })
		this.changeHistory();
        this.getTableData();
      })
    },
    back(){
      if(!this.tableSelectData || this.tableSelectData.length==0){
        this.$message({
            message: '请选择待操作的数据',
            type: 'warning'
          })
        return;
      }
      let ids = [];
      for(let data of this.tableSelectData){
        if(!data.goodsState || data.goodsState!='COMMIT'){
          this.$message({
            message: '待操作的商品中，其的状态只可是【新提交】',
            type: 'warning'
          })
          return;
        }
        ids.push(data.id);
      }
      setGoodsState("RETURN",ids).then(res => {
        this.$message({
            message: '操作成功',
            type: 'success'
          })
		this.changeHistory();
        this.getTableData();
      })
    },
    set(){
      if(!this.tableSelectData || this.tableSelectData.length==0){
        this.$message({
            message: '请选择待操作的数据',
            type: 'warning'
          })
        return;
      }
      let ids = [];
      for(let data of this.tableSelectData){
        ids.push(data.id);
      }

      setIsAid(true,ids).then(res => {
        this.$message({
            message: '操作成功',
            type: 'success'
          })
        this.getTableData();
      })
    },
    cancel(){
      if(!this.tableSelectData || this.tableSelectData.length==0){
        this.$message({
            message: '请选择待操作的数据',
            type: 'warning'
          })
        return;
      }
      let ids = [];
      for(let data of this.tableSelectData){
        ids.push(data.id);
      }

      setIsAid(false,ids).then(res => {
        this.$message({
            message: '操作成功',
            type: 'success'
          })
        this.getTableData();
      })
    },

    openDialog(row){
      this.dataId=row.id;
	  this.supplierName = row.supplierName;
      this.dataDetail={};
      getLocalGoodItemDetail(row.id).then(res => {
        this.dataDetail = res
        this.dialogVisible=true;
      })
    },
    passGood(){
      const ids = [this.dataId];
	  this.dataDetail.goodsState = "PASS";
      setGoodsState("PASS",ids).then(res => {
        this.$message({
            message: '操作成功',
            type: 'success'
          })
        this.dialogVisible=false;
        this.getTableData();
		this.changeHistory();
      })
    },
    backGood(){
      const ids = [this.dataId];
	  // this.dataDetail.goodsState = "RETURN";
      setGoodsState("RETURN",ids).then(res => {
        this.$message({
            message: '操作成功',
            type: 'success'
          })
        this.dialogVisible=false;
        this.getTableData();
		// this.changeHistory();
      })
    },
    upDownGood(type){
	  this.dataDetail.goodsState = type;
      const ids = [this.dataId];
      setGoodsState(type,ids).then(res => {
        this.$message({
            message: '操作成功',
            type: 'success'
          })
        this.dialogVisible=false;
        this.getTableData();
		this.changeHistory();
      })
    },
	
	changeHistory(){
		  this.dataDetail.fkItemId = this.dataDetail.id;
		  this.dataDetail.goodsPrice = this.dataDetail.agreementPrice;
		  this.dataDetail.supplierName = this.supplierName;
		  this.dataDetail.supplierType = 1;
		  systemHis(this.dataDetail).then(res => {
		  })
	}

  },
  created () {
    this.DNS = config.DNS
  },
  mounted () {
    this.init()
  }
}
</script>
<style lang="scss">
.control-box {
  margin-bottom: 10px;
}
.line-height .el-form-item__content {
  line-height: 20px;
}

.dialog-form{
  margin-top: 15px;
}
.dialog-form ::v-deep .el-form-item__label{
  line-height: 30px;
}
.dialog-form ::v-deep .el-form-item__content{
  line-height: 30px;
}
.dialog-form ::v-deep .el-form-item{
  margin-bottom: 12px;
}
.dialog-form img {
  width:100%
}
</style>
